let DynamicsData = require("./DynamicsData");
cc.Class({
    extends: cc.Component,

    properties: {
        bulletMgrNode: cc.Node,
        playerProgressBar: cc.ProgressBar,
        playRole: [cc.SpriteFrame],
        scoreNode: cc.Node,
    },


    onLoad() {
        //触摸事件
        this.node.on(cc.Node.EventType.TOUCH_MOVE, function (event) {
            //获取世界坐标  event.getLocation()
            let wolrdPos = event.getLocation();
            //将世界坐标(绝对坐标)转成本地坐标(相对坐标)
            //将获取的节点的世界坐标转换成相对于父节点的相对坐标，
            let playerPos = this.node.parent.convertToNodeSpaceAR(wolrdPos);
            this.node.x = playerPos.x;
            this.node.y = playerPos.y;
        }, this)
        //玩家发射子弹
        this.schedule(this.fire, 0.2);
        this.playerMaxHp = this.playerHp = 20;
        //获取血条组件
        this.playerProgress = this.playerProgressBar;
        this.playerRole();
    },

    start() {

    },

    update(dt) {

    },

    fire() {
        this.node.zIndex = 1;
        let bulletMgrNodeJs = this.bulletMgrNode.getComponent("BulletMgr");
        //只有设置位置的两个节点的原点是一样的既可以直接设置，否则需要进行转换
        bulletMgrNodeJs.createBullet(this.node.position, "player", "player");
    },

    playerHurt(isOver) {
        if (!isOver) {
            this.playerHp -= 1;
        }
        else if (isOver) {
            let petNode = cc.find("Canvas/player/petMgr/pet");
            if (petNode) {
                petNode.removeFromParent();
            }
            else if (!petNode) {
                this.playerHp = 0;
            }
        }
        this.playerProgress.progress = this.playerHp / this.playerMaxHp;
        if (this.playerHp <= 0) {
            cc.director.loadScene("Over");
            this.node.removeFromParent();
        }
    },

    playerAddHp(hp, score) {
        this.playerHp += hp;
        this.playerProgress.progress = this.playerHp / this.playerMaxHp;
        if (this.playerHp > this.playerMaxHp) {
            this.playerHp = this.playerMaxHp;
        }
        this.scoreNode.getComponent("Score").addScore(score);
    },

    playerRole() {
        let index = DynamicsData.getData("pageIndex");
        this.node.getComponent(cc.Sprite).spriteFrame = this.playRole[index];
    }

});
